package com.example.springbootrbac.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootrbac.entity.AuthEntity;
import com.example.springbootrbac.entity.RoleEntity;
import com.example.springbootrbac.entity.UserEntity;
import com.example.springbootrbac.repository.AuthRepository;
import com.example.springbootrbac.repository.RoleRepository;
import com.example.springbootrbac.repository.UserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource(name = "userRepository")
    private UserRepository userRepository;
    @Resource(name = "roleRepository")
    private RoleRepository roleRepository;
    @Resource(name = "authRepository")
    private AuthRepository authRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 1、根据用户名查询用户信息
        UserEntity user = userRepository.selectOne(new QueryWrapper<UserEntity>()
                .select("id", "username", "password")
                .eq("username", username)
        );
        if (ObjectUtils.isEmpty(user)) {
            return User.withUsername("anonymity")
                    .password("")
                    .authorities(Collections.emptyList())
                    .build();
        }
        // 2、根据用户ID查询角色
        // 查询角色
        List<RoleEntity> roles = roleRepository.selectListByUserId(user.getId());
        // 3、根据角色ID查询权限
        List<AuthEntity> auths = authRepository.selectListByRoleIds(roles.stream()
                .map(RoleEntity::getId).collect(Collectors.toList()));
        // 4、组装成UserDetails对象
        List<GrantedAuthority> authorities = new LinkedList<>();
        for (RoleEntity role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_".concat(role.getRolename())));
        }
        for (AuthEntity auth : auths) {
            authorities.add(new SimpleGrantedAuthority(auth.getUri()));
        }
        return User.withUsername(username).password(user.getPassword()).authorities(authorities).build();
    }
}
